package fun.tan90.easy.binlog.plugin.mqtt.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputResEnum;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEvent;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEventRes;
import fun.tan90.easy.binlog.plugin.common.listener.BinlogEventPluginListener;
import fun.tan90.easy.binlog.plugin.common.model.BinlogData;
import fun.tan90.easy.binlog.plugin.common.model.BinlogOutputRule;
import fun.tan90.easy.binlog.plugin.mqtt.constants.MqttPluginConstants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.noear.dami.Dami;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * description 应用初始化后置处理器，防止 spring 事件被多次执行
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/8/17 8:31
 */
@Slf4j
public class MqttEventProcessor implements BinlogEventPluginListener, ApplicationListener<ApplicationReadyEvent> {

    private final static int QOS = 2;

    private final AtomicBoolean initialized = new AtomicBoolean(false);

    private final LoadingCache<String, MqttClient> mqttClientCache;

    public MqttEventProcessor(LoadingCache<String, MqttClient> mqttClientCache) {
        this.mqttClientCache = mqttClientCache;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (initialized.compareAndSet(false, true)) {
            Dami.<BinlogDataEvent, BinlogDataEventRes>bus().listen(DamiEventConstants.BINLOG_EVENT_TOPIC + outputType(), payload -> {
                BinlogDataEvent binlogDataEvent = payload.getContent();
                String masterCode = binlogDataEvent.getMasterCode();
                List<BinlogData> binlogDataList = binlogDataEvent.getBinlogDataList();
                List<BinlogOutputRule> binlogOutputRules = binlogDataEvent.getBinlogOutputRules();
                for (BinlogOutputRule binlogOutputRule : binlogOutputRules) {
                    String outputRuleCountId = binlogOutputRule.getOutputRuleCountId();
                    String outputCode = binlogOutputRule.getOutputCode();
                    MqttClient mqttClient = mqttClientCache.get(outputCode);
                    if (mqttClient != null) {
                        for (BinlogData binlogData : binlogDataList) {
                            if (filterOutput(binlogOutputRule, binlogData)) {
                                try {
                                    String topic = StrUtil.format(MqttPluginConstants.TOPIC, new HashMap<String, String>(2) {{
                                        put("masterCode", masterCode);
                                        put("eventType", binlogData.getEventType());
                                    }});
                                    mqttClient.publish(topic, JSONUtil.toJsonStr(binlogData).getBytes(StandardCharsets.UTF_8), QOS, false);
                                    reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                } catch (MqttException e) {
                                    reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                    log.error("消息发送失败 {}", e.getMessage());
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public String outputType() {
        return OutputTypeEnum.MQTT.getOutput();
    }
}
